package tenglang.common.httpclient;

import feign.Client;
import feign.httpclient.ApacheHttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
@ConditionalOnClass({ApacheHttpClient.class})
@ConditionalOnProperty(
        value = {"feign.httpclient.enabled"},
        matchIfMissing = true
)
@EnableConfigurationProperties({HttpClientConfig.class})
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class HttpClientFeignConfiguration {

    @Bean
    public Client feignClient(@Autowired HttpClientConfig httpClientConfig,
                              @Autowired CachingSpringLoadBalancerFactory cachingFactory,
                              @Autowired SpringClientFactory clientFactory){
        HttpConnectionPoolUtil connectionPoolUtil=new HttpConnectionPoolUtil(httpClientConfig);
        CloseableHttpClient closeableHttpClient=connectionPoolUtil.getHttpClient();

        LoadBalancerFeignClient loadBalancerFeignClient=
                new LoadBalancerFeignClient(new ApacheHttpClient(closeableHttpClient),cachingFactory,clientFactory);
        return loadBalancerFeignClient;
    }
}
